<template>
  <el-dialog
    v-model="visible"
    :modal="false"
    :close-on-click-modal="false"
    :title="$t('groups.edit')"
    @before-close="onCloseBefore"
    @close="onCloseAoU"
  >
    <el-tabs
      v-model="activeName"
      type="card"
    >
      <el-tab-pane
        :label="$t('user.generalConfiguration')"
        name="first"
      >
        <div class="prods-select-body">
          <el-form
            ref="dataFormRef"
            label-width="120px"
            :model="dataForm"
            :rules="dataRule"
            @submit.prevent
          >
            <el-form-item
              class="el-form-item"
              :label="$t('user.levelName')"
              prop="levelName"
            >
              <el-input
                v-model="dataForm.levelName"
                :placeholder="$t('user.enterGradeName')"
                type="text"
                maxlength="10"
                show-word-limit
              />
            </el-form-item>
            <el-form-item
              ref="imgRef"
              class="el-form-item"
              :label="$t('user.bgImg')"
              prop="img"
            >
              <img-upload
                v-model:modelValue="dataForm.img"
                @update:model-value="onEditImg"
              />
            </el-form-item>
            <el-form-item
              v-if="dataForm.levelType === 1"
              :label="$t('user.paidMemberPrice')"
              prop="needAmount"
              class="el-form-item"
            >
              <el-input
                v-model="dataForm.needAmount"
                :placeholder="$t('user.enterInteger')"
                min="0.01"
                type="number"
                precision="0"
                style="width: 400px"
                oninput="if(value.length>10)value=value.slice(0,10)"
                @change="dataForm.needAmount = onInput(dataForm.needAmount)"
              >
                <template #append>
                  {{ $t('coupon.yuan') }}
                </template>
              </el-input>
            </el-form-item>
            <el-form-item
              v-if="dataForm.levelType === 1"
              :label="$t('user.timeType')"
              prop="termType"
              class="el-form-item"
            >
              <el-radio-group v-model="dataForm.termType">
                <el-radio :label="1">
                  {{ $t('coupon.day') }}
                </el-radio>
                <el-radio :label="2">
                  {{ $t('user.week') }}
                </el-radio>
                <el-radio :label="3">
                  {{ $t('user.month') }}
                </el-radio>
                <el-radio :label="4">
                  {{ $t('user.season') }}
                </el-radio>
                <el-radio :label="5">
                  {{ $t('user.year') }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              class="el-form-item"
              :label="$t('user.requiredGrowthValue')"
              prop="needGrowth"
            >
              <el-input
                v-model="dataForm.needGrowth"
                :placeholder="$t('user.enterInteger')"
                type="number"
                :min="minNeedGrowth"
                :max="maxNeedGrowth"
                precision="0"
                :disabled="dataForm.level === 1 && dataForm.levelType === 0"
                style="width: 400px"
                @change="onChangeNeedGrowth()"
              >
                <template #append>
                  {{ $t('user.growth') }}
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane
        :label="$t('user.equityAllocation')"
        name="third"
      >
        <div class="prods-select-body">
          <!-- native modifier has been removed, please confirm whether the function has been affected  -->
          <el-form
            label-width="30px"
            @submit.prevent
          >
            <el-form-item
              class="el-form-item"
              prop="isFreeFee"
            >
              <el-checkbox v-model="isFreeFee">
                {{ $t('user.selfFreeShipping') }}
              </el-checkbox>
            </el-form-item>
            <el-form-item
              class="el-form-item"
              prop="rateScore"
            >
              <el-checkbox v-model="isRateScore">
                {{ $t('user.pointFeedbackRate') }}
              </el-checkbox>
              <el-input-number
                v-if="isRateScore"
                v-model="dataForm.rateScore"
                :placeholder="$t('user.enterMagnification')"

                :min="1"
                :max="100"
                :precision="2"
                controls-position="right"
              />
            </el-form-item>
            <el-form-item
              class="el-form-item"
              prop="couponList"
            >
              <el-checkbox v-model="isCoupon">
                {{ $t('user.coupons') }}
              </el-checkbox>
              <template v-if="isCoupon">
                <div
                  class="default-btn text-btn select-coupons"
                  @click.prevent="onSelectCouponHandle()"
                >
                  {{ $t('user.selectCoupons') }}
                </div>
                <span
                  v-for="(item,index) in dataForm.couponList"
                  :key="index"
                >
                  <span
                    v-if="index < 2"
                  >{{ item.couponName }}&nbsp;</span>
                </span>
                {{ dataForm.couponList.length>2?'等优惠券':'' }}
              </template>
            </el-form-item>
            <el-form-item
              class="el-form-item"
              prop="presScore"
            >
              <el-checkbox v-model="isPresScore">
                {{ $t('user.bonusPoints') }}
              </el-checkbox>
              <el-input-number
                v-if="isPresScore"
                v-model="dataForm.presScore"
                :placeholder="$t('user.enterInteger')"
                :min="0"
                :precision="0"
                controls-position="right"
              >
                <template #append>
                  {{ $t('order.score') }}
                </template>
              </el-input-number>
            </el-form-item>
            <el-form-item
              class="el-form-item"
              prop="discount"
            >
              <el-checkbox v-model="isDiscount">
                {{ $t('user.discount') }}
              </el-checkbox>
              <el-input-number
                v-if="isDiscount"
                v-model="dataForm.discount"
                :placeholder="$t('user.discountRange')"
                :min="1"
                :max="10"
                :precision="2"

                controls-position="right"
              >
                <template #append>
                  {{ $t('marketing.fold') }}
                </template>
              </el-input-number>
            </el-form-item>
            <el-form-item
              v-if="isDiscount"
              class="el-form-item"
              prop="discountType"
            >
              <el-radio-group v-model="dataForm.discountType">
                <el-radio :label="0">
                  {{ $t('user.allProducts') }}
                </el-radio>
                <el-radio :label="1">
                  {{ $t('user.categoryGoods') }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              v-if="isDiscount && dataForm.discountType === 1"
              class="el-form-item"
              prop="categorys"
            >
              <el-tree
                ref="categoryTreeRef"
                :data="categoryList"
                :props="categoryListTreeProps"
                node-key="categoryId"
                show-checkbox
              />
            </el-form-item>
            <!--其他权益-->
            <el-form-item
              class="el-form-item"
              prop="presScore"
            >
              <el-form-item prop="discountRange">
                <el-checkbox v-model="isOrther">
                  {{ $t('user.otherRights') }}
                </el-checkbox>
                <el-checkbox-group
                  v-if="isOrther"
                  v-model="userRightsIds"
                >
                  <el-checkbox
                    v-for="item in rightsDataList"
                    :key="item.rightsId"
                    style="margin:4px 30px 0 0"
                    :label="item.rightsId"
                    border
                  >
                    {{ item.rightsName }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form-item>
          </el-form>
          <coupon-select
            v-if="couponSelectVisible"
            ref="couponSelectRef"
            :get-way="1"
            @refresh-select-coupon-list="onSelectDistributionCoupon"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <div>
        <div
          class="default-btn"
          @click="onCloseAoU"
        >
          {{ $t('coupon.cancel') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t('coupon.confirm') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { treeDataTranslate } from '@/utils'
import { ElMessage } from 'element-plus'
const emit = defineEmits(['refreshDataList', 'closeAddOrUp'])
const categoryListTreeProps = {
  label: 'categoryName',
  children: 'children'
}
// eslint-disable-next-line no-unused-vars
const validateTime = (rule, value, callback) => {
  const reg = /^[1-9]\d*$/
  if (!reg.test(dataForm.term)) {
    callback(new Error($t('user.integerGreaterThanZero')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const valilevelName = (rule, value, callback) => {
  const reg = /^\s+$/g
  if (reg.test(dataForm.levelName)) {
    callback(new Error($t('user.gradeNmaeCannotEmpty')))
  } else {
    callback()
  }
}
const dataRule = {
  img: [
    { required: true, message: $t('publics.imageNoNull'), trigger: 'blur' }
  ],
  levelName: [
    { required: true, message: $t('user.gradeNmaeCannotEmpty'), trigger: 'blur' },
    { required: true, validator: valilevelName, trigger: 'blur' }
  ],
  term: [
    { required: true, validator: validateTime, trigger: 'blur' }
  ]
}

onActivated(() => {
  onGetDataList()
})
const dataForm = ref({
  id: null,
  level: 0,
  levelName: '',
  levelType: 0,
  needGrowth: 0,
  needAmount: 0,
  term: 1,
  termType: 1,
  img: '',
  discount: 10,
  discountRange: 0,
  discountType: 0,
  presScore: 0,
  rateScore: 1,
  isFreeFee: 0,
  couponList: [],
  userRightsIds: [],
  categoryList: [],
  categorys: []
})
const visible = ref(false)
const activeName = ref('first')
const isRateScore = ref(false)
const isFreeFee = ref(false)
const isCoupon = ref(false)
const isPresScore = ref(false)
const isDiscount = ref(false)
const isOrther = ref(false)
const userRightsIds = ref([])
const init = (userLevels, index) => {
  // 初始化
  visible.value = true
  activeName.value = 'first'
  isRateScore.value = false
  isFreeFee.value = false
  isCoupon.value = false
  isPresScore.value = false
  isDiscount.value = false
  isOrther.value = false
  if (userLevels[index].id) {
    onGetDataList(userLevels, index)
  } else {
    // 保存直接写入数据
    dataForm.value = userLevels[index]
    userRightsIds.value = dataForm.value.userRightsIds
    // 设置所需积分最大最小值
    onSetMinOrMaxNeedGrowth(userLevels, index)
    onGetCategoryDataList()
    onGetRightsDataList()
  }
}
/**
 * 获取初始话数据
 */
const onGetDataList = (userLevels, index) => {
  http({
    url: http.adornUrl('/user/userLevel/info/' + parseInt(userLevels[index].id)),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    dataForm.value = data
    userRightsIds.value = data.userRightsIds
    onSetRightsStatus(data)
    onSetMinOrMaxNeedGrowth(userLevels, index)
    onGetCategoryDataList()
    onGetRightsDataList()
  })
}
/**
 * 获取商品分类列表
 */
const categoryList = ref([])
const categoryTreeRef = ref(null)
const onGetCategoryDataList = () => {
  http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get',
    params: http.adornParams({
      maxGrade: 2
    })
  }).then(({ data }) => {
    categoryList.value = treeDataTranslate(data, 'categoryId', 'parentId')
    if (dataForm.value.discountType === 1) {
      categoryTreeRef.value?.setCheckedKeys(dataForm.value.categorys)
    }
  })
}
/**
 * 获取用户权益列表
 */
const rightsDataList = ref([])

const onGetRightsDataList = () => {
  http({
    url: http.adornUrl('/user/userRights/list'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    rightsDataList.value = data
  })
}
/**
 * 设置所需积分最大最小值
 */
let minNeedGrowth = null
let maxNeedGrowth = null
const onSetMinOrMaxNeedGrowth = (userLevels, index) => {
  if (userLevels[index].level > 1) {
    if (userLevels[index - 1].needGrowth === 1000000000) {
      minNeedGrowth = userLevels[index - 1].needGrowth
    } else {
      minNeedGrowth = userLevels[index - 1].needGrowth + 1
    }
  } else {
    minNeedGrowth = 0
  }
  if (index < userLevels.length - 1 && userLevels[index + 1].needGrowth !== 0) {
    maxNeedGrowth = userLevels[index + 1].needGrowth - 1
  } else {
    maxNeedGrowth = 1000000000
  }
}
/**
 * 显示添加指定优惠券弹框
 */
const couponSelectRef = ref(null)
const couponSelectVisible = ref(false)
const onSelectCouponHandle = () => {
  couponSelectVisible.value = true
  nextTick(() => {
    couponSelectRef.value.init(dataFormRef.value?.couponList)
  })
}
/**
 * 优惠券选择回调
 */
const onSelectDistributionCoupon = (coupons) => {
  if (coupons.length > 0) {
    dataForm.value.couponList = coupons
  } else {
    dataForm.value.couponList = []
    isCoupon.value = false
  }
}
/**
 * 权益选项数据校验
 */
const onSetRights = () => {
  // 邮费
  if (isFreeFee.value) {
    dataForm.value.isFreeFee = 1
  } else {
    dataForm.value.isFreeFee = 0
  }
  // 折扣
  if (!isDiscount.value) {
    dataForm.value.discount = 10
    dataForm.value.discountRange = 0
    dataForm.value.discountType = 0
  }
  // 优惠券
  if (!isCoupon.value) {
    dataForm.value.couponList = []
  }
  // 积分倍率
  if (!isRateScore.value) {
    dataForm.value.rateScore = 1
  }
  // 赠送积分
  if (!isPresScore.value) {
    dataForm.value.presScore = 0
  }
  // 其他权益
  if (!isOrther.value) {
    dataForm.value.userRightsIds = []
  } else {
    dataForm.value.userRightsIds = userRightsIds.value
  }
}

/**
 * 确定事件
 */
const dataFormRef = ref(null)

const onSubmit = () => {
  onSetRights()
  if (dataForm.value.discountType === 1 && categoryTreeRef.value?.getCheckedKeys().length === 0) {
    onErrorMsg($t('user.selectCategory'))
    return
  } else if (dataForm.value.discountType === 1) {
    dataForm.value.categorys = categoryTreeRef.value?.getCheckedKeys()
  }
  dataFormRef.value.validate((valid) => {
    if (!valid) {
      return
    }
    http({
      url: http.adornUrl('/user/userLevel'),
      method: 'put',
      data: http.adornData(dataForm.value)
    }).then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500
      })
      emit('refreshDataList')
    }).catch(() => { })
    dataForm.value = {
      id: null,
      level: 0,
      levelName: '',
      levelType: 0,
      needGrowth: 0,
      needAmount: 0,
      term: 1,
      termType: 1,
      img: '',
      discount: 10,
      discountRange: 0,
      discountType: 0,
      presScore: 0,
      rateScore: 1,
      isFreeFee: 0,
      couponList: [],
      userRightsIds: [],
      categoryList: [],
      categorys: []
    }
    visible.value = false
  })
}
const onSetRightsStatus = (data) => {
  data.isFreeFee === 0 ? isFreeFee.value = false : isFreeFee.value = true
  data.discount === 10 ? isDiscount.value = false : isDiscount.value = true
  data.rateScore === 1 ? isRateScore.value = false : isRateScore.value = true
  data.presScore === 0 ? isPresScore.value = false : isPresScore.value = true
  data.couponList?.length < 1 ? isCoupon.value = false : isCoupon.value = true
  data.userRightsIds?.length < 1 ? isOrther.value = false : isOrther.value = true
}
/**
 * 所需成长值数据变化校验
 */
const onChangeNeedGrowth = () => {
  let num = onSetNumber(dataForm.value.needGrowth)
  if (maxNeedGrowth) {
    num = num > maxNeedGrowth ? maxNeedGrowth : num
  }
  dataForm.value.needGrowth = num < minNeedGrowth ? minNeedGrowth : num
}
/**
 * 所需金额数据变化校验
 */
const onInput = (needAmount) => {
  let amount = parseFloat(needAmount)
  if (isNaN(amount)) {
    return 0.01
  }
  amount = Math.round(needAmount * 100) / 100
  if (amount === 0) {
    amount = 0.01
  }
  let cur = amount.toString()
  let reString = cur.indexOf('.')
  if (reString < 0) {
    reString = cur.length
    cur += '.'
  }
  while (cur.length <= reString + 2) {
    cur += '0'
  }
  if (parseFloat(needAmount) < 0) {
    return 0.01
  }
  return parseFloat(cur).toFixed(2)
}

/**
 * 判断数据
 */
const onSetNumber = (value) => {
  const num = Math.round(value)
  if (num < 0) {
    return 0
  } else {
    return num
  }
}
/**
 * 错误提示框
 */
const onErrorMsg = (message) => {
  ElMessage({
    message,
    type: 'error',
    duration: 1500
  })
}
/**
 * 选择图片
 */
const onEditImg = () => {
  dataFormRef.value.clearValidate(['img'])
}
/**
 * 关闭弹窗
 */
const onCloseBefore = (done) => {
  emit('closeAddOrUp')
  done()
}
const onCloseAoU = () => {
  visible.value = false
}
defineExpose({ init })
</script>
<style scoped>
.el-form-item {
  margin-bottom: 20px !important;
}
.prods-select-body {
  height: 500px;
  overflow: auto;
}
.select-coupons {
  margin-left: 10px;
  margin-right: 10px;
}
</style>
